package com.happy3w.cmds.maven.model;

import lombok.Getter;

import java.text.MessageFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;

@Getter
public class JavaModuleDictionary {
    private List<JavaModule> parentModules;
    private Map<String, JavaModule> moduleMap = new HashMap<>();
    private Map<String, Set<String>> dependOnMap = new HashMap<>();
    private Map<String, Set<String>> dependByMap = new HashMap<>();

    private JavaModuleDictionary() {
    }

    public Stream<JavaModule> streamAllModules() {
        return moduleMap.values().stream();
    }

    private void init(List<JavaModule> parentModules) {
        this.parentModules = parentModules;

        AtomicInteger index = new AtomicInteger(0);
        parentModules.stream()
                .flatMap(JavaModule::streamAllSubModules)
                .forEach(module -> {
                    module.setCode(MessageFormat.format("C{0}", index.getAndIncrement()));
                    moduleMap.put(module.takeKey(), module);
                });
        parentModules.stream()
                .flatMap(JavaModule::streamAllSubModules)
                .forEach(module -> {
                    module.regularDepends(moduleMap);
                    dependOnMap.put(module.takeKey(), new HashSet<>(module.getDependencies()));
                    for (String dependency : module.getDependencies()) {
                        dependByMap.computeIfAbsent(dependency, k -> new HashSet<>())
                                .add(module.takeKey());
                    }
                });
    }

    public static JavaModuleDictionary from(List<JavaModule> parentModules) {
        JavaModuleDictionary dictionary = new JavaModuleDictionary();
        dictionary.init(parentModules);
        return dictionary;
    }
}
